package com.example.zbh.dsliao.ui.adapter;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.android.volley.toolbox.ImageLoader;
import com.example.zbh.dsliao.R;
import com.example.zbh.dsliao.db.entity.CarrouselPic;
import com.example.zbh.dsliao.utils.net.VolleySingleton;

import java.util.List;

/**
 * Created by zbh on 15/11/19.
 */
public class ViewPagerAdapter extends PagerAdapter {
    private List<CarrouselPic> datas;
    private Context context;
    //二级缓存
    private ImageLoader imageLoader;



    /**
     * 添加数据
     * **/
    public void addData(List<CarrouselPic> datas){
        this.datas = datas;
        notifyDataSetChanged();
    }


    /**
     * 构造方法
     * **/
    public ViewPagerAdapter(Context context) {
        this.context = context;
        //初始化二级缓存
        imageLoader = VolleySingleton.getInstance().getImageLoader();
    }


    /**
     * 获得当前界面窗体数
     * **/
    @Override
    public int getCount() {
        return datas != null && datas.size() > 0 ? Integer.MAX_VALUE : 0;
    }

    /**
     * 判断是否由界面产生对象
     * **/
    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }


    /**
     * 销毁position位置的界面
     * **/
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }


    /**
     * 初始化界面
     * **/
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        ImageView viewPagerImg = new ImageView(context);
        viewPagerImg.setScaleType(ImageView.ScaleType.FIT_XY);


        CarrouselPic carousel = datas.get((position % datas.size()));
        String url = carousel.getRandpic();
        ImageLoader.ImageListener imageListener = ImageLoader.getImageListener(viewPagerImg, R.mipmap.cache_img, R.mipmap.cache_img);
        imageLoader.get(url, imageListener);


        container.addView(viewPagerImg);

        return viewPagerImg;
    }
}

